<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑报告' : '生成报告'"
    width="80%"
    :before-close="handleClose"
    class="report-editor-dialog"
  >
    <div class="report-editor">
      <!-- 报告基本信息 -->
      <el-card class="basic-info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>报告基本信息</span>
            <el-button type="primary" size="small" @click="handleAutoGenerate">
              <el-icon><Magic /></el-icon>
              智能生成
            </el-button>
          </div>
        </template>
        
        <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="报告编号" prop="reportId">
                <el-input v-model="formData.reportId" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="患者姓名" prop="patientName">
                <el-input v-model="formData.patientName" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="体检日期" prop="checkupDate">
                <el-input v-model="formData.checkupDate" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报告状态" prop="status">
                <el-select v-model="formData.status" style="width: 100%">
                  <el-option label="草稿" value="draft" />
                  <el-option label="待审核" value="pending" />
                  <el-option label="已审核" value="reviewed" />
                  <el-option label="已发布" value="published" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="主检医生" prop="primaryDoctor">
                <el-select v-model="formData.primaryDoctor" style="width: 100%" filterable>
                  <el-option
                    v-for="doctor in doctors"
                    :key="doctor.id"
                    :label="doctor.name"
                    :value="doctor.name"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="审核医生" prop="reviewDoctor">
                <el-select v-model="formData.reviewDoctor" style="width: 100%" filterable>
                  <el-option
                    v-for="doctor in doctors"
                    :key="doctor.id"
                    :label="doctor.name"
                    :value="doctor.name"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      
      <!-- 体检结果 -->
      <el-card class="results-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>体检结果</span>
            <div class="header-actions">
              <el-button size="small" @click="handleImportResults">
                <el-icon><Upload /></el-icon>
                导入结果
              </el-button>
              <el-button size="small" @click="handleAddResult">
                <el-icon><Plus /></el-icon>
                添加项目
              </el-button>
            </div>
          </div>
        </template>
        
        <div class="results-list">
          <div
            v-for="(result, index) in formData.results"
            :key="index"
            class="result-item"
          >
            <div class="result-header">
              <div class="result-title">
                <el-input
                  v-model="result.itemName"
                  placeholder="检查项目名称"
                  style="width: 200px"
                />
                <el-select
                  v-model="result.category"
                  placeholder="分类"
                  style="width: 120px"
                >
                  <el-option label="血常规" value="blood" />
                  <el-option label="尿常规" value="urine" />
                  <el-option label="肝功能" value="liver" />
                  <el-option label="肾功能" value="kidney" />
                  <el-option label="心电图" value="ecg" />
                  <el-option label="胸片" value="chest" />
                  <el-option label="B超" value="ultrasound" />
                  <el-option label="其他" value="other" />
                </el-select>
              </div>
              <div class="result-actions">
                <el-button
                  type="danger"
                  size="small"
                  @click="handleRemoveResult(index)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
            
            <div class="result-content">
              <el-row :gutter="16">
                <el-col :span="8">
                  <el-form-item label="检查结果">
                    <el-input
                      v-model="result.value"
                      placeholder="检查结果"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="参考范围">
                    <el-input
                      v-model="result.referenceRange"
                      placeholder="参考范围"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="异常标识">
                    <el-select v-model="result.abnormal" style="width: 100%">
                      <el-option label="正常" value="normal" />
                      <el-option label="偏高" value="high" />
                      <el-option label="偏低" value="low" />
                      <el-option label="异常" value="abnormal" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-form-item label="备注">
                <el-input
                  v-model="result.remark"
                  type="textarea"
                  :rows="2"
                  placeholder="检查备注"
                />
              </el-form-item>
            </div>
          </div>
        </div>
      </el-card>
      
      <!-- 报告内容 -->
      <el-card class="content-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>报告内容</span>
            <div class="header-actions">
              <el-button size="small" @click="handleUseTemplate">
                <el-icon><Document /></el-icon>
                使用模板
              </el-button>
              <el-button size="small" @click="handlePreview">
                <el-icon><View /></el-icon>
                预览
              </el-button>
            </div>
          </div>
        </template>
        
        <el-tabs v-model="activeTab" type="border-card">
          <el-tab-pane label="总结" name="summary">
            <el-form-item label="总体评价">
              <el-input
                v-model="formData.summary.overall"
                type="textarea"
                :rows="4"
                placeholder="请输入总体评价"
              />
            </el-form-item>
            
            <el-form-item label="主要异常">
              <el-input
                v-model="formData.summary.abnormalities"
                type="textarea"
                :rows="3"
                placeholder="请输入主要异常情况"
              />
            </el-form-item>
            
            <el-form-item label="健康建议">
              <el-input
                v-model="formData.summary.suggestions"
                type="textarea"
                :rows="4"
                placeholder="请输入健康建议"
              />
            </el-form-item>
          </el-tab-pane>
          
          <el-tab-pane label="详细分析" name="analysis">
            <el-form-item label="详细分析">
              <el-input
                v-model="formData.analysis"
                type="textarea"
                :rows="10"
                placeholder="请输入详细分析内容"
              />
            </el-form-item>
          </el-tab-pane>
          
          <el-tab-pane label="注意事项" name="notes">
            <el-form-item label="注意事项">
              <el-input
                v-model="formData.notes"
                type="textarea"
                :rows="6"
                placeholder="请输入注意事项"
              />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button @click="handleSaveDraft">保存草稿</el-button>
        <el-button type="primary" @click="handleSubmit">
          <el-icon><Check /></el-icon>
          {{ isEdit ? '更新报告' : '生成报告' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  reportData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:visible', 'success'])

// 响应式数据
const formRef = ref()
const activeTab = ref('summary')

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 表单数据
const formData = reactive({
  reportId: '',
  patientName: '',
  checkupDate: '',
  status: 'draft',
  primaryDoctor: '',
  reviewDoctor: '',
  results: [],
  summary: {
    overall: '',
    abnormalities: '',
    suggestions: ''
  },
  analysis: '',
  notes: ''
})

// 表单验证规则
const rules = {
  primaryDoctor: [
    { required: true, message: '请选择主检医生', trigger: 'change' }
  ]
}

// 模拟医生数据
const doctors = ref([
  { id: 1, name: '张医生' },
  { id: 2, name: '李医生' },
  { id: 3, name: '王医生' },
  { id: 4, name: '赵医生' }
])

// 监听对话框显示状态
watch(() => props.visible, (visible) => {
  if (visible) {
    initFormData()
  }
})

// 方法
const initFormData = () => {
  if (props.isEdit && props.reportData) {
    Object.assign(formData, props.reportData)
  } else {
    // 新建报告时的默认数据
    formData.reportId = `RPT${Date.now()}`
    formData.patientName = props.reportData?.patientName || ''
    formData.checkupDate = props.reportData?.checkupDate || ''
    formData.status = 'draft'
    formData.primaryDoctor = ''
    formData.reviewDoctor = ''
    formData.results = props.reportData?.results || []
    formData.summary = {
      overall: '',
      abnormalities: '',
      suggestions: ''
    }
    formData.analysis = ''
    formData.notes = ''
  }
}

const handleClose = () => {
  dialogVisible.value = false
}

const handleAutoGenerate = async () => {
  try {
    ElMessage.info('正在智能生成报告内容...')
    
    // 模拟AI生成
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 生成示例内容
    formData.summary.overall = '本次体检结果显示您的身体状况总体良好，各项主要指标均在正常范围内。'
    formData.summary.abnormalities = '血压略高，建议注意饮食和运动。'
    formData.summary.suggestions = '建议保持规律作息，适量运动，定期复查。'
    formData.analysis = '详细分析：\n1. 血常规检查结果正常\n2. 肝功能指标良好\n3. 血压偏高，需要关注'
    formData.notes = '注意事项：\n1. 控制盐分摄入\n2. 增加有氧运动\n3. 定期监测血压'
    
    ElMessage.success('智能生成完成')
  } catch (error) {
    ElMessage.error('生成失败，请重试')
  }
}

const handleImportResults = () => {
  ElMessage.info('导入体检结果功能开发中')
}

const handleAddResult = () => {
  formData.results.push({
    itemName: '',
    category: '',
    value: '',
    referenceRange: '',
    abnormal: 'normal',
    remark: ''
  })
}

const handleRemoveResult = (index) => {
  formData.results.splice(index, 1)
}

const handleUseTemplate = async () => {
  try {
    const { value } = await ElMessageBox.prompt('请选择报告模板', '使用模板', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputType: 'select',
      inputOptions: {
        'general': '通用体检模板',
        'senior': '老年人体检模板',
        'youth': '青年体检模板',
        'occupation': '职业体检模板'
      }
    })
    
    // 根据模板类型加载内容
    loadTemplate(value)
    ElMessage.success('模板加载成功')
  } catch {
    // 用户取消
  }
}

const loadTemplate = (templateType) => {
  const templates = {
    general: {
      overall: '本次体检结果显示您的身体状况总体良好。',
      abnormalities: '未发现明显异常。',
      suggestions: '建议保持健康的生活方式。'
    },
    senior: {
      overall: '针对您的年龄段，本次体检结果基本正常。',
      abnormalities: '部分指标需要关注。',
      suggestions: '建议定期体检，注意慢性病预防。'
    }
  }
  
  const template = templates[templateType] || templates.general
  Object.assign(formData.summary, template)
}

const handlePreview = () => {
  emit('preview', formData)
}

const handleSaveDraft = async () => {
  try {
    formData.status = 'draft'
    await saveReport()
    ElMessage.success('草稿保存成功')
  } catch (error) {
    ElMessage.error('保存失败，请重试')
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    await saveReport()
    ElMessage.success(props.isEdit ? '报告更新成功' : '报告生成成功')
    emit('success')
    handleClose()
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

const saveReport = async () => {
  // 模拟API调用
  await new Promise(resolve => setTimeout(resolve, 1000))
  
  // 这里应该调用实际的API
  console.log('保存报告数据:', formData)
}
</script>

<style scoped>
.report-editor-dialog :deep(.el-dialog__body) {
  padding: 20px;
  max-height: 80vh;
  overflow-y: auto;
}

.report-editor {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.basic-info-card,
.results-card,
.content-card {
  border: 1px solid #e4e7ed;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.results-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.result-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  background: #fafafa;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.result-title {
  display: flex;
  gap: 12px;
  align-items: center;
}

.result-content {
  background: #ffffff;
  padding: 16px;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .report-editor-dialog {
    width: 95% !important;
  }
  
  .report-editor-dialog :deep(.el-dialog__body) {
    padding: 15px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .result-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .result-title {
    flex-direction: column;
    gap: 8px;
    width: 100%;
  }
  
  .result-title .el-input,
  .result-title .el-select {
    width: 100% !important;
  }
  
  .dialog-footer {
    flex-direction: column;
  }
  
  .dialog-footer .el-button {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .result-content .el-row {
    flex-direction: column;
  }
  
  .result-content .el-col {
    width: 100% !important;
    margin-bottom: 12px;
  }
}
</style>